package com.glacier.example.atomic;

import com.glacier.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicStampedReference;

@Slf4j
@ThreadSafe
public class AtomicExample7 {

    // 请求总数
    public static int clientTotal = 5000;

    public static AtomicStampedReference<Integer> count = new AtomicStampedReference<>(0, 0);

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int num = i;
            executorService.execute(() -> {
                int add = num % 2 == 0 ? 1 : -1;
                boolean success;
                do {
                    int reference = count.getReference();
                    int stamp = count.getStamp();
                    success = count.compareAndSet(reference, reference + add, stamp, stamp + 1);
                    log.info("count:{}, 版本号：{}，结果：{}", count.getReference(), count.getStamp(), success);
                } while (!success);

                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}, 版本号：{}", count.getReference(), count.getStamp());
    }

}
